package xyz.xtgl.config.helper;

import common.core.util.CommonUtil;
import common.core.util.CustomizeRuntimeException;
import common.core.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常捕获处理
 * @author liubo
 * @created 2019-12-26 11:17
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义异常
     */
    @ExceptionHandler(CustomizeRuntimeException.class)
    @ResponseBody
    public Result customizeRuntimeException(CustomizeRuntimeException e) {
        log.error("自定义异常",e);
        if(CommonUtil.isNotEmpty(e.getData())&&e.getData() instanceof Result){
            return (Result) e.getData();
        }
        return Result.exception(e.getMessage());
    }

    @ExceptionHandler  //处理其他异常
    @ResponseBody
    public Result exception(Exception e){
        log.error("全局异常捕获",e);
        int count = 0; //只打印15行的错误堆栈
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            if(count++ > 13) break;
        }
        return Result.exception("系统错误请联系管理员");
    }

}